package com.security.control.web.async;

import com.security.control.core.utils.RandomUtils;
import com.security.control.web.async.entity.MockQueue;
import com.security.control.web.async.holder.DeferredResultsHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.Callable;

/**
 * @author imoot@gamil.com
 * @date 2018/12/15 0015 16:40
 */
@RestController
@RequestMapping("/order")
public class AsyncController {

    private static final Logger log = LoggerFactory.getLogger(AsyncController.class);

    //注入deferred需要的类
    @Autowired
    private MockQueue mockQueue;
    @Autowired
    private DeferredResultsHolder deferredResultsHolder;

    @GetMapping("/synchro")
    public String synchro() throws Exception {
        log.info("主线程开始");
        Thread.sleep(1000);
        log.info("主线程返回");
        return "success";
    }

    //使用Runnable异步处理rest服务
    //问题：必须使用主线程调用副线程
    @GetMapping("/runnbale")
    public Callable<String> runnbale() throws Exception {
        log.info("主线程开始");
        Callable<String> result = new Callable<String>() {
            @Override
            public String call() throws Exception {
                log.info("副线程开始");
                Thread.sleep(1000);
                log.info("副线程返回");
                return "success";
            }
        };
        log.info("主线程返回");
        return result;
    }

    //模拟消息队列使用deferred异步处理rest服务
    @GetMapping("/deferred")
    public DeferredResult<String> deferred() throws Exception {
        log.info("主线程开始");
        String orderNumber = RandomUtils.randomNumeric(8);
        mockQueue.setPlaceOrder(orderNumber);
        DeferredResult<String> result = new DeferredResult<>();
        deferredResultsHolder.getMap().put(orderNumber,result);
        log.info("主线程返回");
        return result;
    }

}
